
class_name QueuePlan
extends ColorRect




@onready var vbox = $ScrollCR/Scroll/VBox
@onready var scroll = $ScrollCR/Scroll
@onready var temp_unit_item = $ScrollCR/TempUnitItem




func _ready() -> void:
	scroll.get_v_scroll_bar().modulate.a = 0
	scroll.get_h_scroll_bar().modulate.a = 0




## 更新数据
func update(_new_list: Array[Unit]) -> void:
	var units: Dictionary = get_unit()
	# 重置 scroll 偏移
	scroll.scroll_vertical = 0
	
	# 先添加
	for index in range(0, _new_list.size()):
		if not units.has(_new_list[index]):
			add_unit(_new_list[index])
	
	# 获取新的
	units = get_unit()
	
	# 排序
	for index in range(0, _new_list.size()):
		vbox.move_child(units[_new_list[index]], index)




## 添加 unit
func add_unit(_unit: Unit) -> void:
	# 拷贝模板
	var temp: TemplateSelectItem = temp_unit_item.duplicate()
	vbox.add_child(temp)
	temp.save_object = _unit
	
	# 设置头像并根据 unit 的 icon 颜色来设置头像的颜色
	var icon: TextureRect = temp.get_node("Icon")
	icon.texture = load(_unit.profile_photo)
	icon.modulate = _unit.icon.modulate
	
	temp.show()
	
	# 连接信号，unit 开始行动时
	_unit.action_start_signal.connect(func (_unit: Unit) -> void:
		temp.rr.border_color = Color8(255, 255, 255)
		var offset: int = (temp.position.y + temp.size.y) - (scroll.size.y / 2)
		
		if offset > 0:
			scroll.scroll_vertical = offset
		
		scroll.scroll_horizontal = 0
	)
	
	# 连接信号，unit 结束行动时
	_unit.action_end_siganl.connect(func (_unit: Unit) -> void:
		temp.rr.border_color = Color8(0, 0, 0)
	)




## 删除 unit
func remove_unit(_unit: Unit) -> void:
	var units: Dictionary = get_unit()
	
	if units.has(_unit):
		var temp: TemplateSelectItem = units[_unit]
		temp.save_object = null
		temp.queue_free()
		
		units.erase(_unit)




## 获取 unit
## 返回一个字典，该字典以 unit : temp 来返回
func get_unit() -> Dictionary:
	var result: Dictionary = {}
	
	for item in vbox.get_children():
		result[item.save_object] = item
	
	return result
